<style>
    .div-key{text-align: center;}
</style>
<div class="row-fluid clearfix">
    <div class="col-sm-12 column">
        <ul class="breadcrumb">
            <li>
                <a href="index.html">首页</a>
            </li>
            <li class="active">
                设备密钥下载
           </li>
        </ul>
    </div>
    <div class="col-sm-12 column">
        <div class="col-sm-12 alert alert-success div-alert" id="events-result"></div>
        <div class="col-sm-12 div-page">
            <div class="col-sm-12 ">
                <div class=" progress ">
                    <div class="progress-bar progress-bar-info" role="progressbar" style="width: 0%;"></div>
                </div>
                <div class="div-key ">
                    <button id="btnDownload" type="button" role="button" class="btn btn-Data btn-primary">
                        <span class="glyphicon glyphicon-download"></span> 密钥下载</button>
                </div>
                <div>
                    <input type="hidden" id="ProTerm_id" name="ProTerm_id" />
                    <input type="hidden" id="ProPad_id" name="ProPad_id" />
                    <input type="hidden" id="SysPubKey" name="SysPubKey" />
                    <input type="hidden" id="TermTmk" name="TermTmk" />
                    <input type="hidden" id="PadTmk" name="PadTmk" />
                    <input type="hidden" id="PubKey" name="PubKey" />
                    <input type="hidden" id="PrvKey" name="PrvKey" />
                    <input type="hidden" id="TermTpk" name="TermTpk" />
                    <input type="hidden" id="TermTak" name="TermTak" />
                    <input type="hidden" id="PadTpk" name="PadTpk" />
                    <input type="hidden" id="PadTak" name="PadTak" />
                    <input type="hidden" id="IsSuccess" name="IsSuccess" value="successed" />
                </div>
            </div>
        </div>

        <!-- #遮罩层 --->
        <div class="modal fade" id="modal-OcxDownload" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <div class="modal-title" id="myModalLabel">
                            控件下载
                        </div>
                    </div>
                    <form id="validForm" method="post" class="form-horizontal layer_msg">
                    <div class="modal-body">
                            <div class="form-group">
                                <div class="col-sm-2"></div>
                                <div class="col-sm-8 modal-msg">

                                </div>
                                <div class="col-sm-2"></div>
                            </div>
                    </div>
                    <div class="modal-footer">
                        <button id="modal-btn-close" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>
<script>

$(function () {
    var timeout;

    // 控件检查
    GetOCXVersion();

    // 密钥下载开始
    // $("#btnDownload").click(DownloadKey);
    $("#btnDownload").click(Step10);

});

// 更新进度条和消息提示
function updateProgressBar(value,msg){
    $("#events-result").text(msg);
    var obj = $('.progress-bar');
    if(''!=value){
        obj.attr('style','width: '+value+'%;').text(value+'%');
        if(100==value){
            obj.removeClass('progress-bar-info');
            obj.addClass('progress-bar-success');
            $("#btnDownload").attr("disabled", false).addClass("btn-primary");
        }
        else{
            obj.removeClass('progress-bar-danger');
            obj.removeClass('progress-bar-success');
            obj.addClass('progress-bar-info');
            $("#btnDownload").attr("disabled", true).removeClass("btn-primary");
        }
    }
    else{
        obj.removeClass('progress-bar-info');
        obj.addClass('progress-bar-danger');
        $("#btnDownload").attr("disabled", false).addClass("btn-primary");
    }
}

// 获取控件版本号
function GetOCXVersion() {
    try {
        if(isIE()) {
            // 此浏览器为 IE
            var OCXVersion = NDV_OCX.GetOCXVersion(); // 获取控件版本号
            if (OCXVersion.substr(4, 5) != "1.0.3" && OCXVersion.substr(4, 5) != "1.0.4"){
                $(".modal-msg").html('<a href="../ocx/V1.0.3KJV.exe">控件安装包V1.0.3KJV.exe<br/>(控件版本不匹配，请重新下载控件，下载完成后双击安装,安装完成后重启浏览器即可)</a>');
                $('#modal-OcxDownload').modal('show');
            }else{
                updateProgressBar(0,"系统准备就绪，请确认终端和密码键盘已连接，点击“密钥下载”，开始进行终端密钥下载。");
                $(".div-alert").show();
                $("#btnDownload").attr("disabled", false).addClass("btn-primary");
            }
        }
        else {
            // 非 IE
            $(".modal-msg").html('控件仅支持IE8及以上版本浏览器。');
            $('#modal-OcxDownload').modal('show');
        }
    }
    catch (ex)// catch the ex
    {
        console.log(ex);
        $(".modal-msg").html('控件未安装或者浏览器设置错误。<a href="../ocx/V1.0.3KJV.exe">控件安装包V1.0.3KJV.exe<br/>(首次使用请点击此处下载控件，下载完成后双击安装,安装完成后重启浏览器即可)</a>');
        $('#modal-OcxDownload').modal('show');
    }
}

function ErrStep(ex) {
    console.log(ex);
    updateProgressBar('',ex);
}

function Step10() {
    try {
        updateProgressBar(10,"开始密钥下载流程。串口检查中，请稍后……");
        // 强制关闭串口
        CloseCOM();
        // 打开串口
        OpenCOM();
        timeout=window.setTimeout("Step20()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step20() {
    try {
        updateProgressBar(20,"串口打开正常。终端号、密码键盘号检查中，请稍后……");
        // 读取终端号，并写入页面数据域
        $("#ProTerm_id").val(ReadTermID());
        // 读取密码键盘号，并写入页面数据域
        $("#ProPad_id").val(ReadSafeID());
        timeout=window.setTimeout("Step30()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step30() {
    try {
        updateProgressBar(30,"终端号、密码键盘号正常。绑定状态检查中，请稍后……");
        // 设备绑定状态检查
        CheckBind();
        timeout=window.setTimeout("Step40()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step40() {
    try {
        updateProgressBar(40,"终端未绑定可使用，主密钥获取中，请稍后……");
        // 获取主密钥
        GetKey();
        timeout=window.setTimeout("Step50()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step50() {
    try {
        updateProgressBar(50,"主密钥获取成功，主密钥写入中，请稍后……");
        // 写入主密钥保护密钥
        WritePK();
        // 写入主密钥
        WriteMK();
        timeout=window.setTimeout("Step60()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step60() {
    try {
        updateProgressBar(60,"主密钥写入成功，工作密钥写入中，请稍后……");
        // 写入工作密钥
        WriteWk();
        timeout=window.setTimeout("Step70()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step70() {
    try {
        updateProgressBar(70,"工作密钥写入成功，系统公钥获取中，请稍后……");
        // 获取系统公钥
        GetSysPubKey();
        timeout=window.setTimeout("Step80()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step80() {
    try {
        updateProgressBar(80,"系统公钥获取成功，公私钥对写入中，请稍后……");
        // 写入公私钥对
        WriteRSAKey();
        timeout=window.setTimeout("Step90()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step90() {
    try {
        updateProgressBar(90,"公私钥对写入成功，数据库检查中，请稍后……");
        // 把主密钥和终端公钥及工作密钥存入数据库
        WriteKeyToDB();
        timeout=window.setTimeout("Step100()",300);
    }
    catch (ex)// catch the ex
    {
        ErrStep(ex);
    }
}

function Step100() {
    updateProgressBar(100,"密钥下载成功。");
    window.clearTimeout(timeout);
}

// 关闭串口
function CloseCOM() {
    var ret = NDV_OCX.CloseCOMport();
    if (ret != '0000') {
        throw new Error( ret + "串口关闭失败，请重试" );
    }
}

// 打开串口
function OpenCOM() {
    var readResult = false;
    for (var i = 0; i < 10; i++) {
        var ret = NDV_OCX.OpenCOMport("COM" + i, "9600");
        if (ret == '0000') {
            readResult = true;
            break;
        }
    }
    if(!readResult) {
        throw new Error( "串口打开失败，请检查串口设置并重试" );
    }
}

// 读取终端序列号
function ReadTermID() {
    var TermID = NDV_OCX.UploadTermID();
    if ( TermID != undefined && TermID.length == 20 ) {
        return TermID;
    } else {
        throw new Error( TermID + "读取终端序列号失败" );
    }
}

// 读取密码键盘序列号
function ReadSafeID() {
    var SafeID = NDV_OCX.UploadSafeID();
    if ( SafeID != undefined && SafeID.length == 16 ) {
        return SafeID;
    } else {
        throw new Error( SafeID + "读取密码键盘序列号失败" );
    }
}

// 设备绑定状态检查
function CheckBind(){
    var SafeID = $("#ProPad_id").val();
    var TermID = $("#ProTerm_id").val();
    $.ajax({
        async: false,
        url: globalUrl+'api/DownloadKey?IsSafeID='+SafeID+"&IsTermID="+TermID,
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if(!resp.result) {
                throw new Error( "设备已绑定状态，请先解除绑定" );
            }
        },
        error: function () {
            throw new Error( "查询绑定数据失败，请重试" );
        }
    });
}

// 写入主密钥保护密钥
function WritePK() {
    var ret = NDV_OCX.DownloadPK("000102030405060708090A0B0C0D0E0F");
    if (ret != '0000') {
        throw new Error( ret + "主密钥保护密钥下载失败，请重试" );
    }
}

// 获取主密钥
function GetKey() {
    var SafeID = $("#ProPad_id").val();
    $.ajax({
        async: false,
        url: globalUrl+'api/DownloadKey?SafeDevId='+ SafeID,
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                var jsonObj = eval("(" + resp.msg + ")");

                if (jsonObj.ViewData.TermTmk != '' && jsonObj.ViewData.PadTmk != ''
                        && jsonObj.ViewData.PubKey != '' && jsonObj.ViewData.PrvKey != ''
                        && jsonObj.ViewData.TermTpk != '' && jsonObj.ViewData.TermTak != ''
                        && jsonObj.ViewData.PadTpk != '' && jsonObj.ViewData.PadTak != '') {
                    $("#TermTmk").val(jsonObj.ViewData.TermTmk);
                    $("#PadTmk").val(jsonObj.ViewData.PadTmk);
                    $("#PubKey").val(jsonObj.ViewData.PubKey);
                    $("#PrvKey").val(jsonObj.ViewData.PrvKey);
                    $("#TermTpk").val(jsonObj.ViewData.TermTpk);
                    $("#TermTak").val(jsonObj.ViewData.TermTak);
                    $("#PadTpk").val(jsonObj.ViewData.PadTpk);
                    $("#PadTak").val(jsonObj.ViewData.PadTak);
                } else {
                    throw new Error( "主密钥下载失败，，请重试" );
                }

            } else {
                throw new Error( "主密钥下载失败，，请重试" );
            }
        },
        error: function () {
            throw new Error( "主密钥下载失败，，请重试" );
        }
    });

}

// 写入主密钥
function WriteMK() {
    var TermTmk = $("#TermTmk").val();
    var ret = NDV_OCX.DownloadMK("0", TermTmk);
    if (ret != '0000') {
        throw new Error( ret + "主密钥写入失败，请重试" );
    }
}

// 写入工作密钥
function WriteWk() {
    var TermTpk = $("#TermTpk").val();
    var TermTak = $("#TermTak").val();
    var NewTermTpk = TermTpk + TermTpk.substr(0,16);
    var NewTermTak = TermTak + TermTak.substr(0,16);

    var ret= NDV_OCX.DownloadWK("0", NewTermTpk, NewTermTak, NewTermTak);
    if (ret != '0000') {
        throw new Error( ret + "工作密钥写入失败，请重试" );
    }
}

// 获取系统公钥
function GetSysPubKey() {
    $.ajax({
        async: false,
        url: globalUrl+'api/DownloadKey/Getsecure_sys_key',
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                var jsonObj = resp.msg;
                if (jsonObj.replace(/\s+/g, "") != "" && jsonObj != "undefined") {
                    $("#SysPubKey").val(jsonObj);
                }
                else{
                    throw new Error( "获取系统公钥失败，请重试" );
                }
            }
            else{
                throw new Error( "获取系统公钥失败，请重试" );
            }
        },
        error: function () {
            throw new Error( "获取系统公钥失败，请重试" );
        }
    });
}

// 写入公私钥对
function WriteRSAKey() {
    var SysPubKey = $("#SysPubKey").val();
    var PubKey = $("#PubKey").val();
    var PrvKey = $("#PrvKey").val();

    var ret = NDV_OCX.Download_RSA_Key(SysPubKey, PubKey, PrvKey);
    if (ret != '0000') {
        throw new Error( ret + "公私钥对写入失败，请重试" );
    }
}

function WriteKeyToDB() {
    var PadTmk = $("#PadTmk").val();
    var PubKey = $("#PubKey").val();
    var ProTerm_id = $("#ProTerm_id").val();
    var ProPad_id = $("#ProPad_id").val();
    var PadTpk = $("#PadTpk").val();
    var PadTak = $("#PadTak").val();
    $.ajax({
        async: false,
        url: globalUrl+'api/DownloadKey',
        data: {
            PadTmk: PadTmk,
            PubKey: PubKey,
            TermID: ProTerm_id,
            Pad_id: ProPad_id,
            ProTerm_id: ProTerm_id,
            ProPad_id: ProPad_id,
            PadTpk: PadTpk,
            PadTak: PadTak
        },
        type: 'post',
        dataType: "json",
        success: function (resp) {
            if (!resp.result) {
                throw new Error( "密钥写入数据库失败，请重试" );
            }
        },
        error: function () {
            throw new Error( "密钥写入数据库失败，请重试" );
        }
    });
}
</script>